package com.bjc.core.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bjc.base.core.BaseServiceImpl;
import com.bjc.base.core.IBaseDao;
import com.bjc.base.utils.StringUtil;
import com.bjc.core.bean.request.PermissionReqVO;
import com.bjc.core.bean.response.PermissionVO;
import com.bjc.core.dao.IPermissionDao;
import com.bjc.core.service.IPermissionService;

/**
 * 系统权限Service
 * 
 * @author 许自辉
 * @date 2017年8月2日
 */
@Service
public class PermissionImpl extends BaseServiceImpl<PermissionReqVO, PermissionVO> implements IPermissionService {

	private IPermissionDao permissionDao;

	@Autowired
	@Override
	public void setBaseDao(IBaseDao<PermissionReqVO, PermissionVO> baseDao) {
		this.baseDao = baseDao;
		this.permissionDao = (IPermissionDao) baseDao;
	}

	@Override
	public void initPermission(PermissionReqVO permissionReqVO) {
		String path = permissionReqVO.getPath();
		String code = permissionReqVO.getCode();
		if (!StringUtil.isNullOrEmpty(path) && !StringUtil.isNullOrEmpty(code)) {
			String[] paths = path.split("/");
			PermissionVO one = null;
			for (int i = 0; i < paths.length; i++) {
				PermissionReqVO p = new PermissionReqVO();
				p.setCode(paths[i]);
				p.setType(0);
				if (i == 0) {
					// 如果路径是第一个
					p.setParentId(0);
					one = permissionDao.get(p);
					// 如果第一个路径没有则添加
					if (one == null) {
						permissionDao.insert(p);
						one = permissionDao.get(p);
					} else {
						permissionDao.update(p);
					}
				} else {
					p.setParentId(one.getId());
					one = permissionDao.get(p);
					if (one == null) {
						permissionDao.insert(p);
						one = permissionDao.get(p);
					} else {
						permissionDao.update(p);
					}
				}
			}

			PermissionReqVO p = new PermissionReqVO();
			p.setParentId(one.getId());
			p.setCode(permissionReqVO.getCode());
			p.setType(1);
			one = permissionDao.get(p);
			if (one == null) {
				permissionDao.insert(p);
			} else {
				permissionDao.update(p);
			}

		}

	}

	@Override
	public void deleteDestroy() {
		permissionDao.deleteDestroy();
	}
}
